package com.liesheng.haylou.common;

import com.liesheng.haylou.base.BaseFunActivity;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Date:2019/11/6
 * <p>
 * Author:wuzhiguang
 * <p>
 * Description: rxJava线程操作
 */
public final class RxHelper {
    private RxHelper() {
    }

    public static <T> Observable<T> createIoActionObservable(Observable.OnSubscribe<T> f) {
        return Observable.create(f)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public static abstract class SingleEmitSubscriber<T> extends Subscriber<T> {
        @Override
        public void onCompleted() {
        }
    }

    public static <T> Subscription runInThread(BaseFunActivity baseFunActivity, final ISimperRxListener<T> rxListener) {

        Subscription subscription = Observable.create(new Observable.OnSubscribe<T>() {
            @Override
            public void call(Subscriber<? super T> subscriber) {
                subscriber.onNext(rxListener.call());
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<T>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        rxListener.onError(e);
                    }

                    @Override
                    public void onNext(T t) {
                        rxListener.onNext(t);
                        this.unsubscribe();
                    }

                });

        if (subscription != null)
            baseFunActivity.addSubscription(subscription);
        return subscription;
    }

    public interface ISimperRxListener<T> {
        //子线程中运行
        T call();

        //主线程中服运行
        void onNext(T t);

        //异常
        void onError(Throwable e);
    }
}
